﻿using System.Collections.Generic;
using System.Drawing;
using System.Linq;

namespace PlusPlusPaint.Layers.VisualObjects
{
    // Sealed due to Deserialize method eating all ints.
    sealed class LineSegmentGroup: DynamicallyGeneratedVisualObject
    {
        #region member vars
        List<Point> pointList = new List<Point>();
        List<LineSegment> lineList = new List<LineSegment>();
        #endregion

        #region public methods
        public void AddPoint(Point p)
        {
            pointList.Add(p);
            if (pointList.Count > 1)
                lineList.Add(new LineSegment(pointList[pointList.Count - 2], pointList[pointList.Count - 1]));
        }
        #endregion

        #region overrides
        protected override string ObjectTypeName
        {
            get
            {
                return "LineSegmentGroup";
            }
        }

        public override SerializedObject Serialize()
        {
            SerializedObject so = base.Serialize();
            foreach (Point p in pointList)
            {
                so.UnnamedInts.Add(p.X);
                so.UnnamedInts.Add(p.Y);
            }
            return so;
        }

        public override void Deserialize(SerializedObject s)
        {
            base.Deserialize(s);
            while (s.UnnamedInts.Count > 1) // Let's assume there's an even number and more than two in total.
            {
                Point next = new Point(s.UnnamedInts[0], s.UnnamedInts[1]);
                if (this.pointList.Count != 0)
                    this.lineList.Add(new LineSegment(pointList.Last(), next));
                this.pointList.Add(next);
                s.UnnamedInts.RemoveAt(1);
                s.UnnamedInts.RemoveAt(0);
            }
        }

        public override bool PositionIsInHitbox(Point p)
        {
            return lineList.Any((line) => line.PositionIsInHitbox(p));
        }

        public override IVisualObject Clone()
        {
            LineSegmentGroup ls = new LineSegmentGroup();
            foreach (LineSegment line in lineList)
            {
                ls.lineList.Add(line.Clone() as LineSegment);
                ls.pointList.AddRange(pointList.ToArray());
            }
            return ls;
        }

        public override void BurnOn(Image im)
        {
            using (Pen p = new Pen(this.Colour, this.BrushSize))
                Graphics.FromImage(im).DrawLines(p, pointList.ToArray());
        }
        #endregion
    }
}
